package com.lagou.repository.impl;

import com.lagou.annotations.AutoWired;
import com.lagou.annotations.Repository;
import com.lagou.pojo.Account;
import com.lagou.repository.AccountRepository;
import com.lagou.utils.ConnectionUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * 账号实体的数据库访问实现
 */
@Repository("accountRepository")
public class AccountRepositoryImpl implements AccountRepository {
    @AutoWired
    private ConnectionUtils connectionUtils;

    public Account selectAccountByCardId(String cardId) throws Exception {
        Connection connection = connectionUtils.getCurrentThreadConnection();
        String sql = "select * from account where cardId = ?";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setString(1, cardId);

        ResultSet resultSet = preparedStatement.executeQuery();

        Account account = new Account();

        while (resultSet.next()) {
            account.setCardId(resultSet.getString("cardId"));
            account.setName(resultSet.getString("name"));
            account.setMoney(resultSet.getInt("money"));
        }

        resultSet.close();
        preparedStatement.close();

        return account;
    }

    public int updateAccountByCardId(Account account) throws Exception {
        Connection connection = connectionUtils.getCurrentThreadConnection();
        String sql = "update account set money = ? where cardId = ?";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setInt(1, account.getMoney());
        preparedStatement.setString(2, account.getCardId());

        int result = preparedStatement.executeUpdate();

        preparedStatement.close();

        return result;
    }
}
